<?php 
namespace app\admin\controller;
use think\Controller;
use catetree\Catetree;

class Category extends Controller{

	public function index(){
		$cate = new Catetree();
		$data = db('category')->select();
		$catetree_res = $cate->catetree($data);
		$this->assign([
			'data'	=>$catetree_res,
		]);
		return view();
	}

	public function add(){
		$cate = new Catetree();
		if(request()->isPost()){
			$data = input('post.');
			if($_FILES['cate_img']['tmp_name']){
				$data['cate_img'] = $this->upload();
			}
			$res = db('category')->insert($data);
			if($res){
				$this->success('商品分类添加成功！',url('index'));
			}else{
				$this->error('商品分类添加失败！');
			}
		}
		$_cate_res=db('category')->select();
		$cate_res = $cate->catetree($_cate_res);
		$this->assign([
			'cate_res'	=>$cate_res,
		]);
		return view();
	}

	public function edit($id){
		$res = db('category')->find($id);
		
        $catetree=new Catetree();
    	if(request()->isPost()){
    		$data=input('post.');
             //处理图片上传
            if($_FILES['cate_img']['tmp_name']){
                $data['cate_img']=$this->upload();
                $categorys=db('category')->field('cate_img')->find($data['id']);
                if($categorys['cate_img']){
                    $imgSrc=IMG_UPLOADS.$categorys['cate_img'];
                    if(file_exists($imgSrc)){
                        @unlink($imgSrc);
                    }
                }
            }
    		$save=db('category')->update($data);
    		if($save !== false){
    			$this->success('修改分类成功！','index');
    		}else{
    			$this->error('修改分类失败！');
    		}
    		return;
    	}

		$categoryRes = db('category')->select();
		$cate_res = $catetree->catetree($categoryRes);
		$this->assign([
			'cate_res'	=>$cate_res,
			'res'		=>$res,
		]);
		return view();
	}

	public function del($id){
		$cate = new Catetree();
		$category = db('category');
		$sonids = $cate->childrenids($id,$category);
		$sonids[] = (int)$id;
		foreach($sonids as $k=>$v){
			$res = $category->find($v);
			if($res['cate_img']){
				$imgurl = ROOT_PATH.'public/static/upload/'.$res['cate_img'];
				if(file_exists($imgurl)){
					@unlink($imgurl);
				}
			}
		}

		$d_res = $category->delete($sonids);
		if($d_res){
			$this->success('商品分类删除成功！',url('index'));
		}else{
			$this->error('商品分类删除失败！');
		}
	}

	public function upload(){
		$file=request()->file('cate_img');
		if($file){
			$info=$file->move(ROOT_PATH.'public'.DS.'static'.DS.'upload');
			if($info){
				return $info->getSaveName();
			}else{
				echo $file->getError();
				die;
			}
		}
	}

}